package sf.database.jdbc.type;

import java.io.Reader;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

public class ClobType implements TypeHandler<Clob> {

    public Clob get(ResultSet rs, String colName) throws SQLException {
        return rs.getClob(colName);
    }

    public Clob get(ResultSet rs, int index) throws SQLException {
        return rs.getClob(index);
    }

    public Clob get(CallableStatement rs, int index) throws SQLException {
        return rs.getClob(index);
    }

    @Override
    public Clob get(CallableStatement cs, String parameterName) throws SQLException {
        return cs.getClob(parameterName);
    }

    @Override
    public void update(ResultSet rs, String columnLabel, Object value) throws SQLException {
        if (Clob.class.isAssignableFrom(value.getClass())) {
            rs.updateClob(columnLabel, (Clob) value);
        } else if (Reader.class.isAssignableFrom(value.getClass())) {
            rs.updateClob(columnLabel, (Reader) value);
        }
    }

    @Override
    public void update(ResultSet rs, int columnIndex, Object value) throws SQLException {
        if (Clob.class.isAssignableFrom(value.getClass())) {
            rs.updateClob(columnIndex, (Clob) value);
        } else if (Reader.class.isAssignableFrom(value.getClass())) {
            rs.updateClob(columnIndex, (Reader) value);
        }
    }

    public Object set(PreparedStatement ps, Object obj, int i) throws SQLException {
        if (null == obj) {
            ps.setNull(i, getSqlType());
        } else {
            if (Clob.class.isAssignableFrom(obj.getClass())) {
                ps.setClob(i, (Clob) obj);
            } else if (Reader.class.isAssignableFrom(obj.getClass())) {
                ps.setClob(i, (Reader) obj);
            }
        }
        return null;
    }

    @Override
    public Object set(CallableStatement cs, Object obj, String parameterName) throws SQLException {
        if (null == obj) {
            cs.setNull(parameterName, getSqlType());
        } else {
            if (Clob.class.isAssignableFrom(obj.getClass())) {
                cs.setClob(parameterName, (Clob) obj);
            } else if (Reader.class.isAssignableFrom(obj.getClass())) {
                cs.setClob(parameterName, (Reader) obj);
            }
        }
        return null;
    }

    @Override
    public int getSqlType() {
        return Types.CLOB;
    }

    @Override
    public Class<Clob> getDefaultJavaType() {
        return Clob.class;
    }

}